package kitwee.com.kanpad;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.EmptyUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.zhouwei.library.CustomPopWindow;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kitwee.com.kanpad.bean.BomvoListAdapter;
import kitwee.com.kanpad.bean.DepartmentInfo;
import kitwee.com.kanpad.bean.DepartmentListAdapter;
import kitwee.com.kanpad.bean.ListDetailBean;
import kitwee.com.kanpad.bean.LoginBean;
import kitwee.com.kanpad.bean.MessageListAdapter;
import kitwee.com.kanpad.bean.MyAdapter;
import kitwee.com.kanpad.bean.MyStopAdapter;
import kitwee.com.kanpad.bean.TaskListBean;
import kitwee.com.kanpad.common.KanpadStrings;
import kitwee.com.kanpad.widget.CustomDialog;
import okhttp3.Call;
import utils.FlavorHelper;
import utils.SPUtils;

public class ListDeatailActivity extends BaseActivity implements View.OnClickListener, BomvoListAdapter.OnItemClickLitener {
    @BindView(R.id.tv_task_name)
    TextView tvTaskName;
    @BindView(R.id.tv_task_status)
    TextView tvTaskStatus;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_product_number)
    TextView tvProductNumber;
    @BindView(R.id.tv_device_name)
    TextView tvDeviceName;
    @BindView(R.id.tv_task_start_time)
    TextView tvTaskStartTime;
    @BindView(R.id.tv_task_end_time)
    TextView tvTaskEndTime;
    @BindView(R.id.tv_actual_number)
    TextView tvActualNumber;
    @BindView(R.id.tv_actual_number_person)
    TextView tvActualNumberPerson;
    @BindView(R.id.tv_plan_number)
    TextView tvPlanNumber;
    @BindView(R.id.rl_news)
    RecyclerView rlNews;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.go_back)
    Button goBack;
    @BindView(R.id.bt_login_out)
    Button btLoginOut;
    @BindView(R.id.progress)
    ProgressBar progress;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.rl_reason)
    RelativeLayout rlReason;
    @BindView(R.id.rl_container)
    RelativeLayout rlContainer;
    @BindView(R.id.tv_ac_task_start_time)
    TextView tvAcTaskStartTime;
    @BindView(R.id.tv_ac_task_end_time)
    TextView tvAcTaskEndTime;
    @BindView(R.id.tv_people)
    TextView tvPeople;
    @BindView(R.id.change_shift)
    Button changeShift;
    @BindView(R.id.recycleview_department)
    RecyclerView recycleviewDepartment;
    @BindView(R.id.sure)
    TextView sure;
    @BindView(R.id.cancel)
    TextView cancel;
    @BindView(R.id.rl_department)
    LinearLayout rlDepartment;
    @BindView(R.id.submit)
    Button submit;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.recycleview_reason)
    RecyclerView recycleviewReason;
    @BindView(R.id.sub_number)
    EditText subNumber;

    @BindView(R.id.sub_good_number)
    EditText subGoodNumber;
    @BindView(R.id.sub_bad_number)
    EditText subBadNumber;
    @BindView(R.id.sub_time)
    EditText subTime;


    @BindView(R.id.tv_bad_pro)
    TextView tvBadPro;
    @BindView(R.id.tv_good_pro)
    TextView tvGoodPro;
    @BindView(R.id.tv_runtime)
    TextView tvRunTime;
    @BindView(R.id.sub_sure)
    TextView subSure;
    @BindView(R.id.sub_cancel)
    TextView subCancel;
    @BindView(R.id.rl_submit)
    RelativeLayout rlSubmit;
    @BindView(R.id.calculator)
    Button calculator;


    private TaskListBean.RowsBean rowsBean;
    private MessageListAdapter messageListAdapter;
    private CustomPopWindow mListPopWindow;
    private List<ListDetailBean.PauseStatusRemarksBean> pauserowsBeenTrue = new ArrayList<>();
    private List<ListDetailBean.StopStatusRemarksBean> stoprowsBeenTrue = new ArrayList<>();
    private String task_status_remarks;
    private List<DepartmentInfo.DataBean.RowsBean> departmentList;
    private DepartmentListAdapter departmentListAdapter;
    private String departmentID;
    private InputMethodManager imm;
    private String endpoint;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        MyMultiDexApplication.getInstance().addActivity(this);
        initData();
        super.onCreate(savedInstanceState);
        hideBottomUIMenu();
        setContentView(R.layout.activity_task_detail);


        ButterKnife.bind(this);
        endpoint = BuildConfig.API_ENDPOINT;
        initDepartmentRecycle();
        recycleviewReason.setLayoutManager(new GridLayoutManager(this, 3));

        initRecycleview(task_status_remarks);


        setLastData();
        initMessageList();
        timer = new Timer();
        dialog = new CustomDialog(this);

        imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
    }


    List<ListDetailBean.KanbanMessageVOListBean> mesList;

    //消息通知
    private void initMessageList() {
        mesList = new ArrayList<>();
        final LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
        rlNews.setLayoutManager(mLinearLayoutManager);
        messageListAdapter = new MessageListAdapter(this, mesList);
        rlNews.setAdapter(messageListAdapter);
    }

    List<ListDetailBean.ProductBOMVOListBean> mlist;


    //上个界面
    private void initData() {
        Intent intent = this.getIntent();
        rowsBean = (TaskListBean.RowsBean) intent.getSerializableExtra("rowsBean");
        task_status_remarks = rowsBean.getBase_task_status();
    }

    //设置正常数据
    private void setLastData() {
        if (rowsBean != null) {
            //顶部
            tvTaskName.setText(getString(R.string.task_name) + rowsBean.getTask_name());
            tvOrder.setText(getString(R.string.task_order) + rowsBean.getOrder_number());
            tvProductNumber.setText(getString(R.string.task_product_number) + rowsBean.getProduct_number());
            tvDeviceName.setText(getString(R.string.task_device_number) + rowsBean.getDevice_name());
            tvPeople.setText("负责人 : " + rowsBean.getLeader_name());
            if (rowsBean.getActual_start_time_text() != null) {
                tvAcTaskStartTime.setText("实际开始 : " + rowsBean.getActual_start_time_text());
            } else {
                tvAcTaskStartTime.setText("实际开始 : 暂无");
            }
            tvAcTaskStartTime.setText("实际开始 : " + rowsBean.getActual_start_time_text());
            if (rowsBean.getActual_end_time_text() != null) {
                tvAcTaskEndTime.setText("实际结束 : " + rowsBean.getActual_end_time_text());
            } else {
                tvAcTaskEndTime.setVisibility(View.GONE);
//                tvAcTaskEndTime.setText("未结束 : " );
            }

        }
    }


    private int calculateDpToPx(int padding_in_dp) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (padding_in_dp * scale + 0.5f);
    }


    /**
     * 弹出退出输入哐.
     *
     * @param view
     */
    private void showPhoPopwindow(final View view) {
        Intent intent = new Intent();
        intent.setClass(this, PopDialogActivity.class);
        startActivity(intent);
        hideBottomUIMenu();
    }

    private Timer timer;
    private TimerTask task;

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        if (timer != null) {
            if (task != null) {
                task.cancel();
            }
            task = new TimerTask() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = TIMED;
                    handler.sendMessage(message);
                }
            };
            timer.schedule(task, 1000, 1000 * 60); //启动timer

        } else {
            initNetData();
        }

        initDepartment();
    }

    private String departName;

    /**
     * 交接班list
     */
    private void initDepartmentRecycle() {
        departmentList = new ArrayList<>();
        recycleviewDepartment.setLayoutManager(new GridLayoutManager(this, 3));
        departmentListAdapter = new DepartmentListAdapter(departmentList, this);
        recycleviewDepartment.setAdapter(departmentListAdapter);
        departmentListAdapter.setOnItemClickLitener(new DepartmentListAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                departmentID = departmentList.get(position).getId();
                departName = departmentList.get(position).getName();
            }
        });

    }

    private void succession(String id) {
        String user = SPUtils.getString(this, "user");
        String key = SPUtils.getString(this, "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);
        OkHttpUtils.get()
                .tag(this)
//                .url(KanpadStrings.HOSTURL + "/deviceStatusRecords/stopTask")
                .url(endpoint + "/deviceStatusRecords/stopTask")
                .addParams("pun", user)
                .addParams("pd", digest)
                .addParams("t", timer)
                .addParams("leader_name", id)
                .addParams("task_id", rowsBean.getId())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogUtils.e("换班失败 ; " + e.getMessage());
                        ToastUtils.showShort("换班失败,请重试");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject jsonObj = JSON.parseObject(response);
                        String data = jsonObj.getString("statusCode");
                        if (TextUtils.equals("200", data)) {
                            LogUtils.e("换班成功 ; " + response);
                            finish();
                        } else {
                            LogUtils.e("换班失败 ; " + jsonObj.getString("message"));
                            ToastUtils.showShort("换班失败,请重试");
                        }

                    }
                });

    }

    /**
     * 交接班人.
     */
    private void initDepartment() {
        String user = SPUtils.getString(this, "user");
        String key = SPUtils.getString(this, "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);

        OkHttpUtils.get()
                .tag(this)
//                .url(BuildConfig.API_ENDPOINT_NORMAL + "/deviceStatusRecords/findUserList")
                .url(endpoint + "/deviceStatusRecords/findUserList")
                .addParams("pun", user)
                .addParams("pd", digest)
                .addParams("t", timer)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogUtils.e("交接班联系人 ; " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        LogUtils.e("交接班联系人 : " + response);
//                        departmentList.addAll("");
                        JSONObject jsonObj = JSON.parseObject(response);
                        JSONObject data = jsonObj.getJSONObject("data");
                        JSONArray rows = data.getJSONArray("rows");
                        List<DepartmentInfo.DataBean.RowsBean> departList = JSON.parseArray(rows.toString(), DepartmentInfo.DataBean.RowsBean.class);

                        for (int i = 0; i < departList.size(); i++) {
                            LogUtils.e("开机员............" + departList.get(i).getDepartment_name() + " ... " + departList.get(i).getName());
                            if (TextUtils.equals("开机员", departList.get(i).getDepartment_name())) {
                                departmentList.add(departList.get(i));
                            }
                        }

                        departmentListAdapter.notifyDataSetChanged();
                    }
                });
    }

    private CustomDialog dialog = null;
    private static final int TIMED = 1;
    private static final int SUCCESS = 2;
    private static final int STOP = 3;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TIMED:
                    initNetData();
                    break;
                case SUCCESS:
                    String response = (String) msg.obj;
                    setPager(response);
                    break;
            }
        }
    };

    private void setPager(String response) {
        try {
            progress.setVisibility(View.GONE);
            //设置sop上面的text
            ListDetailBean listDetailBean = JSON.parseObject(response, ListDetailBean.class);

            List<ListDetailBean.PauseStatusRemarksBean> pauseStatusRemarksBeen = listDetailBean.getPauseStatusRemarks();
            //暂停原因
            if (pauseStatusRemarksBeen != null) {
                pauserowsBeenTrue.clear();
                pauserowsBeenTrue.addAll(pauseStatusRemarksBeen);
            }
            List<ListDetailBean.StopStatusRemarksBean> stopStatusRemarksBeen = listDetailBean.getStopStatusRemarks();
            if (stopStatusRemarksBeen != null) {
                stoprowsBeenTrue.addAll(stopStatusRemarksBeen);
            }
            List<ListDetailBean.KanbanMessageVOListBean> kanbanMessageVOList = listDetailBean.getKanbanMessageVOList();
            //设置消息列表
            if (kanbanMessageVOList != null) {
                setMessageList(kanbanMessageVOList);
            }
            List<ListDetailBean.TaskDetailChangeStatusBtnListBean> rowsBeen = listDetailBean.getTaskDetailChangeStatusBtnList();

            if (rowsBeen != null) {
                llContent.removeAllViews();
                if (isAUTO) {
                    rowsBeen.add(new ListDetailBean.TaskDetailChangeStatusBtnListBean("修改暂停原因", "pause"));
                    addButtonView(rowsBeen);
                } else {

                    addButtonView(rowsBeen);
                }

            } else {
                llContent.setVisibility(View.GONE);
            }
            setSOPText(listDetailBean);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initNetData() {
        if (rowsBean != null) {
            if (!isFinishing()) {
//                dialog.show();
                progress.setVisibility(View.VISIBLE);
                String task_id = rowsBean.getId();
                String user = SPUtils.getString(this, "user");
                String key = SPUtils.getString(this, "key");
                final long time = System.currentTimeMillis();
                final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
                String timer = String.valueOf(time);
                OkHttpUtils.get()
                        .tag(this)
//                        .url(KanpadStrings.HOSTURL + "/productionTask/getProductionTaskDetail")
                        .url(endpoint + "/productionTask/getProductionTaskDetail")
                        .addParams("EQ_task_id", task_id)
                        .addParams("pun", user)
                        .addParams("pd", digest)
                        .addParams("t", timer)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                e.printStackTrace();
                                LogUtils.e("请求任务详情失败 ：" + call + " ;错误 ：" + e + "; id :" + id);
//                                dialog.dismiss();
                                progress.setVisibility(View.GONE);
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                Message msg = Message.obtain();
                                LogUtils.e("任务详情请求成功： success" + response);
                                if (response != null) {
                                    msg.obj = response;
                                    msg.what = SUCCESS;
                                    handler.sendMessage(msg);
                                }
                            }
                        });
            }
        }
    }


    //设置sop上面的数据
    private void setSOPText(ListDetailBean listDetailBean) {
        if (listDetailBean != null) {
            tvTaskStatus.setText(getString(R.string.task_status) + listDetailBean.getTask_status_value());
            //sop顶部.
            tvTaskStartTime.setText(getString(R.string.task_start) + listDetailBean.getScheduled_start_time_text());
            tvTaskEndTime.setText(getString(R.string.task_end) + listDetailBean.getScheduled_end_time_text());

            tvActualNumber.setText(getString(R.string.actual_number) + (int) Math.round(listDetailBean.getActual_production()));
            tvPlanNumber.setText(getString(R.string.plan_number) + (int) Math.round(listDetailBean.getScheduled_production()));
            if (listDetailBean.getActual_production_person() != null) {
                tvActualNumberPerson.setText(getString(R.string.actual_number_person) + listDetailBean.getActual_production_person());
            } else {
                tvActualNumberPerson.setText(getString(R.string.actual_number_person) + " 暂无");
            }

            if (listDetailBean.getGoodProductAmount() != null) {
                tvGoodPro.setText(getString(R.string.good_pro) + listDetailBean.getGoodProductAmount());
            } else {
                tvGoodPro.setText(getString(R.string.good_pro) + "暂无");
            }

            if (listDetailBean.getBadProductAmount() != null) {
                tvBadPro.setText(getString(R.string.bad_pro) + listDetailBean.getBadProductAmount());
            } else {
                tvBadPro.setText(getString(R.string.bad_pro) + "暂无");
            }

            if (listDetailBean.getRun_time() != null) {
                tvRunTime.setText(getString(R.string.run_time) + listDetailBean.getRun_time() + "/分钟");
            } else {
                tvRunTime.setText(getString(R.string.run_time) + "暂无");
            }

            //报工
            if (listDetailBean.getActual_production_person() == null) {
                subNumber.setHint("实际产量 : " + listDetailBean.getActual_production());
            } else {
                subNumber.setHint("实际产量 : " + listDetailBean.getActual_production_person());
            }

            if (listDetailBean.getGoodProductAmount() != null) {
                subGoodNumber.setHint("良品 : " + listDetailBean.getGoodProductAmount());
            } else {
                subGoodNumber.setHint("良品 : " + (int) Math.round(listDetailBean.getActual_production()));
            }

            if (listDetailBean.getBadProductAmount() != null) {
                subBadNumber.setHint("不良品 : " + listDetailBean.getBadProductAmount());
            } else {
                subBadNumber.setHint("不良品 : " + "0");
            }
            if (rowsBean.getActual_start_time_text() != null) {
                long timeSpanByNow = TimeUtils.getTimeSpanByNow(rowsBean.getActual_start_time_text().toString(), TimeConstants.MIN);
                subTime.setHint("实际开始时间 : " + timeSpanByNow);
            } else {
                subTime.setHint("实际开始时间 : 无");
            }


        }

    }

    private void setMessageList(List<ListDetailBean.KanbanMessageVOListBean> rowsBeen) {
        if (mesList.size() > 0) {
            mesList.clear();
            mesList.addAll(rowsBeen);
            messageListAdapter.notifyDataSetChanged();
        } else {
            mesList.addAll(rowsBeen);
            messageListAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void onDestroy() {
        if (timer != null) {// 停止timer
            timer.cancel();
            timer = null;
        }
        if (mListPopWindow != null) {
            mListPopWindow.dissmiss();
            mListPopWindow = null;
        }
        handler.removeCallbacksAndMessages(null);
        if (ListDeatailActivity.this.isFinishing() && dialog != null) {
            dialog.dismiss();
        }

        if (task != null) {
            task.cancel();
        }

        super.onDestroy();
        hideBottomUIMenu();
    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.STATUS_BAR_HIDDEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }


    private boolean isComplete;
    private boolean isChangeWork;

    @OnClick({R.id.go_back, R.id.bt_login_out, R.id.rl_container, R.id.change_shift, R.id.cancel, R.id.sure
            , R.id.submit, R.id.sub_cancel, R.id.sub_sure, R.id.calculator})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.calculator:
//                Intent intent = new Intent();
//                intent.setClassName("com.android.calculator2", "com.android.calculator2.Calculator");
//                startActivity(intent);
                break;
            case R.id.rl_container:
                rlReason.setVisibility(View.GONE);
                rlDepartment.setVisibility(View.GONE);
                rlSubmit.setVisibility(View.GONE);
                imm.hideSoftInputFromWindow(subNumber.getWindowToken(), 0);
                imm.hideSoftInputFromWindow(subGoodNumber.getWindowToken(), 0);
                imm.hideSoftInputFromWindow(subNumber.getWindowToken(), 0);
                imm.hideSoftInputFromWindow(subBadNumber.getWindowToken(), 0);
                imm.hideSoftInputFromWindow(subTime.getWindowToken(), 0);

                break;
            case R.id.status_start_not_start:
                isAUTO = false;
                LogUtils.e("not_started");
                setTaskStatus("not_started");
                break;
            case R.id.status_prepare:
                isAUTO = false;
                LogUtils.e("started");
                setTaskStatus("started");
                break;
            case R.id.status_fix:
                isAUTO = false;
                LogUtils.e("debug_machine");
                setTaskStatus("debug_machine");
                break;
            case R.id.status_product_start:
                LogUtils.e("in_process");
                setTaskStatus("in_process");
                break;
            case R.id.status_finsh:
                isAUTO = false;
                LogUtils.e("complete");
                isComplete = true;
                rlDepartment.setVisibility(View.GONE);
                rlReason.setVisibility(View.GONE);
                rlSubmit.setVisibility(View.VISIBLE);

                break;
            case R.id.status_stop:
                isAUTO = false;
                LogUtils.e("stop");
                rlReason.setVisibility(View.VISIBLE);
                initRecycleview("stop");
//                showPopListView(view, "stop");
                break;
            case R.id.status_pause:
                rlReason.setVisibility(View.VISIBLE);
                initRecycleview("pause");
//                showPopListView(view, "pause");
                break;
            case R.id.go_back:
                LogUtils.e("详情返回 ： success");
                this.finish();
                break;
            case R.id.bt_login_out:
                showPhoPopwindow(view);
                break;
            case R.id.change_shift:
                isChangeWork = true;
                rlDepartment.setVisibility(View.GONE);
                rlReason.setVisibility(View.GONE);
                rlSubmit.setVisibility(View.VISIBLE);
                break;
            case R.id.cancel:
                rlDepartment.setVisibility(View.GONE);
                break;

            case R.id.sure:
                rlDepartment.setVisibility(View.GONE);
                succession(departmentID);
                break;

            case R.id.submit:
                rlSubmit.setVisibility(View.VISIBLE);
                rlDepartment.setVisibility(View.GONE);
                rlReason.setVisibility(View.GONE);
                break;
            case R.id.sub_sure:
                String s = subNumber.getText().toString();
                String s1 = subBadNumber.getText().toString();
                String s2 = subGoodNumber.getText().toString();
                String s3 = subTime.getText().toString();
                if (TextUtils.equals("", s) && TextUtils.equals("", s1) && TextUtils.equals("", s2) && TextUtils.equals("", s3)) {
                    ToastUtils.showShort("报工参数不能为空");
                } else {
                    submitProduction();

                }
                break;
            case R.id.sub_cancel:

                if (isChangeWork) {
                    isChangeWork = false;
                }

                if (isComplete) {
                    isComplete = false;
                }
                rlSubmit.setVisibility(View.GONE);
                break;

        }
    }

    private void submitProduction() {

        if (subNumber.getText().toString() != null) {
            String number = subNumber.getText().toString();
            String goodNumber = subGoodNumber.getText().toString();
            String badNumber = subBadNumber.getText().toString();
            String continuedTime = subTime.getText().toString();

            String user = SPUtils.getString(this, "user");
            String key = SPUtils.getString(this, "key");
            final long time = System.currentTimeMillis();
            final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
            String timer = String.valueOf(time);
            OkHttpUtils.get()
                    .tag(this)
//                    .url(KanpadStrings.HOSTURL + "/deviceStatusRecords/addproduction")
                    .url(endpoint + "/deviceStatusRecords/addproduction")
                    .addParams("pun", user)
                    .addParams("pd", digest)
                    .addParams("t", timer)
                    .addParams("confirmed_production", number)
                    .addParams("badProductAmount", badNumber)
                    .addParams("goodProductAmount", goodNumber)
                    .addParams("run_time", continuedTime)
                    .addParams("taskId", rowsBean.getId())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            LogUtils.e("报工失败 ; " + e.getMessage());
                        }

                        @Override
                        public void onResponse(String response, int id) {

                            JSONObject jsonObj = JSON.parseObject(response);
                            String data = jsonObj.getString("statusCode");
                            if (TextUtils.equals("200", data)) {
                                LogUtils.e("报工成功 ; " + response);
                                if (isChangeWork) {
                                    rlSubmit.setVisibility(View.GONE);
                                    rlDepartment.setVisibility(View.VISIBLE);
                                }

                                if (isComplete) {
                                    setTaskStatus("complete");
                                    finish();
                                }

                                if (isChangeWork) {
                                    rlDepartment.setVisibility(View.VISIBLE);
                                }


                                setSubText();

                            } else {
                                if (isChangeWork) {
                                    isChangeWork = false;
                                }

                                if (isComplete) {
                                    isComplete = false;
                                }
                            }


                        }
                    });
        }

    }

    /**
     * 重置报工界面
     */
    private void setSubText() {
        subNumber.setText("");
        subBadNumber.setText("");
        subGoodNumber.setText("");
        subTime.setText("");
    }

    private void initRecycleview(String what) {

        if (TextUtils.equals("pause", what)) {
            isAUTO = true;
            MyAdapter adapter = new MyAdapter(this, pauserowsBeenTrue);
            if (pauserowsBeenTrue != null && pauserowsBeenTrue.size() > 0) {
                adapter.setData(pauserowsBeenTrue);
                recycleviewReason.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                adapter.setOnItemClickLitener(this);
            }
        } else {
            isAUTO = false;
            MyStopAdapter adapter = new MyStopAdapter();
            if (stoprowsBeenTrue != null && stoprowsBeenTrue.size() > 0) {
                adapter.setData(stoprowsBeenTrue);
                recycleviewReason.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                adapter.setOnItemClickLitener(new BomvoListAdapter.OnItemClickLitener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        rlReason.setVisibility(View.GONE);
                        String dict_key = stoprowsBeenTrue.get(position).getDict_key();
                        String dick_value = stoprowsBeenTrue.get(position).getDict_value();
                        setTaskStatusStopAndPause(dict_key, dick_value);
                    }

                    @Override
                    public void onItemLongClick(View view, int position) {
                    }
                });
            }
        }
    }

    private void handleListView(View contentView, String what) {
        RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.recycleview);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        if (TextUtils.equals("pause", what)) {
            MyAdapter adapter = new MyAdapter(this, pauserowsBeenTrue);
            if (pauserowsBeenTrue != null && pauserowsBeenTrue.size() > 0) {
                adapter.setData(pauserowsBeenTrue);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                adapter.setOnItemClickLitener(new BomvoListAdapter.OnItemClickLitener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        String dict_key = pauserowsBeenTrue.get(position).getDict_key();
                        String dick_value = pauserowsBeenTrue.get(position).getDict_value();
                        mListPopWindow.dissmiss();
                        setTaskStatusStopAndPause(dict_key, dick_value);
                    }

                    @Override
                    public void onItemLongClick(View view, int position) {
                    }
                });
            } else {
                ToastUtils.showShort("请刷新再试");
            }
        } else {
            MyStopAdapter adapter = new MyStopAdapter();
            if (stoprowsBeenTrue != null && stoprowsBeenTrue.size() > 0) {
                adapter.setData(stoprowsBeenTrue);
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                adapter.setOnItemClickLitener(new BomvoListAdapter.OnItemClickLitener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        String dict_key = stoprowsBeenTrue.get(position).getDict_key();
                        String dick_value = stoprowsBeenTrue.get(position).getDict_value();
                        mListPopWindow.dissmiss();
                        setTaskStatusStopAndPause(dict_key, dick_value);
                    }

                    @Override
                    public void onItemLongClick(View view, int position) {
                    }
                });
            } else {
                ToastUtils.showShort("请刷新再试");
            }
        }
    }

    private boolean isAUTO = false;

    /**
     * 暂停原因
     *
     * @param status_key
     * @param value
     */
    private void setTaskStatusStopAndPause(String status_key, String value) {
        progress.setVisibility(View.GONE);
        String task_id = rowsBean.getId();
        String user = SPUtils.getString(this, "user");
        String key = SPUtils.getString(this, "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);
        OkHttpUtils.get()
                .tag(this)
//                .url(KanpadStrings.HOSTURL + "/productionTask/changeTaskStatus")
                .url(endpoint + "/productionTask/changeTaskStatus")
                .addParams("EQ_task_id", task_id)
                .addParams("EQ_task_status_key", status_key)
                .addParams("EQ_task_status_remarks", value)
                .addParams("pd", digest)
                .addParams("pun", user)
                .addParams("t", timer)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        progress.setVisibility(View.GONE);
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        progress.setVisibility(View.GONE);
                        LoginBean loginBean = JSONObject.parseObject(response, LoginBean.class);
                        if (TextUtils.equals("200", loginBean.getStatusCode())) {
                            ToastUtils.showShort("" + loginBean.getMessage());
                            rlReason.setVisibility(View.GONE);
                            isAUTO = true;
                            initNetData();
                        } else if (TextUtils.equals("300", loginBean.getStatusCode())) {
                            ToastUtils.showShort("" + loginBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 设置状态.
     *
     * @param status_key
     */
    private void setTaskStatus(String status_key) {
        String task_id = rowsBean.getId();
        String user = SPUtils.getString(this, "user");
        String key = SPUtils.getString(this, "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);
        OkHttpUtils.get()
                .tag(this)
//                .url(KanpadStrings.HOSTURL + "/productionTask/changeTaskStatus")
                .url(BuildConfig.API_ENDPOINT + "/productionTask/changeTaskStatus")
                .addParams("EQ_task_id", task_id)
                .addParams("EQ_task_status_key", status_key)
                .addParams("pd", digest)
                .addParams("pun", user)
                .addParams("t", timer)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        ToastUtils.showShort("完成失败,请重试.");
                        LogUtils.e("切换状态失败 : " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        isAUTO = false;
                        LoginBean loginBean = JSONObject.parseObject(response, LoginBean.class);
                        if (TextUtils.equals("200", loginBean.getStatusCode())) {
                            ToastUtils.showShort(loginBean.getMessage() + "");
                            initNetData();
                        } else if (TextUtils.equals("300", loginBean.getStatusCode())) {
                            ToastUtils.showShort(loginBean.getMessage() + "");
                            LogUtils.e("操作失败 : " + loginBean.getMessage());
                        }
                    }
                });
    }

    @Override
    protected void onPause() {
        super.onPause();
        hideBottomUIMenu();
        MobclickAgent.onPause(this);
    }


    //添加右边的按钮
    private void addButtonView(List<ListDetailBean.TaskDetailChangeStatusBtnListBean> rowsBeen) {
        if (rowsBeen.size() > 0) {
            // TODO 动态添加布局(java方式)
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            LinearLayout view = new LinearLayout(this);
            view.setLayoutParams(lp);//设置布局参数
            view.setOrientation(LinearLayout.VERTICAL);// 设置子View的Linearlayout// 为垂直方向布局
            LinearLayout.LayoutParams vlp = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            vlp.setMargins(0, 15, 0, 0);

            for (int i = 0; i < rowsBeen.size(); i++) {
                addTestView(rowsBeen.get(i).getStatus_key(), rowsBeen.get(i).getStatus_value(), vlp);
            }
        }

    }

    private void addTestView(String key, String value, LinearLayout.LayoutParams vlp) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int widthPix = displayMetrics.widthPixels;
        int heightPix = displayMetrics.heightPixels;

        TextView textWhat = new TextView(this);
        textWhat.setLayoutParams(vlp);
        if (widthPix < 1000) {
            textWhat.setTextSize(20);
            textWhat.setPadding(calculateDpToPx(5), calculateDpToPx(10), calculateDpToPx(5), calculateDpToPx(10));
        } else {
            textWhat.setTextSize(30);
            textWhat.setPadding(calculateDpToPx(5), calculateDpToPx(20), calculateDpToPx(5), calculateDpToPx(20));
        }


        setTextId(textWhat, key, value);
        textWhat.setTextColor(getResources().getColor(R.color.white));
        textWhat.setBackgroundColor(getResources().getColor(R.color.item_back));
        textWhat.setGravity(Gravity.CENTER_HORIZONTAL);

        textWhat.setOnClickListener(this);
        llContent.addView(textWhat);

    }

    private void setTextId(TextView textWhat, String key, String value) {
        if (key != null) {
            if (TextUtils.equals("pause", key)) {//暂停
                textWhat.setId(R.id.status_pause);
                textWhat.setText(value);
            } else if (TextUtils.equals("not_started", key)) {  //未开始
                textWhat.setId(R.id.status_start_not_start);
                textWhat.setText(value);
            } else if (TextUtils.equals("started", key)) {  //开始
                textWhat.setId(R.id.status_prepare);
                textWhat.setText(value);
            } else if (TextUtils.equals("debug_machine", key)) {  //调机
                textWhat.setId(R.id.status_fix);
                textWhat.setText(value);
            } else if (TextUtils.equals("in_process", key)) {  //生产
                textWhat.setId(R.id.status_product_start);
                textWhat.setText(value);
            } else if (TextUtils.equals("complete", key)) {  //完成
                textWhat.setId(R.id.status_finsh);
                textWhat.setText(value);
            } else if (TextUtils.equals("stop", key)) {  //中止
                textWhat.setId(R.id.status_stop);
                textWhat.setText(value);
            }
        }
    }


    @Override
    public void onItemClick(View view, int position) {
        rlReason.setVisibility(View.GONE);
        String dict_key = pauserowsBeenTrue.get(position).getDict_key();
        String dick_value = pauserowsBeenTrue.get(position).getDict_value();
        setTaskStatusStopAndPause(dict_key, dick_value);
    }

    @Override
    public void onItemLongClick(View view, int position) {

    }
}
